package fr.snac.notification;

import java.util.Timer;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import fr.snac.bm.BonjourActivity;
import fr.snac.bm.R;
import fr.snac.utils.Constants;

public class CheckService extends Service{

	int interval;
	Timer timer;
	SharedPreferences settings;
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		timer = new Timer();
		settings = getSharedPreferences(Constants.SETTINGS_PREFERENCES, 0);
		interval = settings.getInt(Constants.SETTINGS_INTERVAL, 5);
		timer.schedule(new CheckTimerTask(CheckService.this), 0, interval * 60 * 1000);
		
		return Service.START_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		timer.cancel();
		super.onDestroy();
	}
	
	@SuppressLint("NewApi")
	public void buildNotification(){
		
		long[] vibration = {1000, 500, 2000, 500};
		Intent resultIntent = new Intent(getApplicationContext(), BonjourActivity.class);

		Notification.Builder builder = new Notification.Builder(getApplicationContext());
		builder.setContentTitle(getResources().getString(R.string.app_name));
		builder.setContentText(getResources().getString(R.string.mamdameAvailable));
		builder.setSmallIcon(R.drawable.ic_bm);
		builder.setVibrate(vibration);
		builder.setOnlyAlertOnce(true);

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		stackBuilder.addParentStack(BonjourActivity.class);
		stackBuilder.addNextIntent(resultIntent);
		
		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
		builder.setContentIntent(resultPendingIntent);

		Notification notification = builder.build();

		NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		manager.notify(Constants.NOTIFICATION_TAG, 0, notification);
	}
}
